var express = require('express');
var router = express.Router();
var fs = require("fs");
var createPng = require('./createPng');
var Readable = require('stream').Readable;
/* GET home page. */
router.get('/', function(req, res) {
  // res.render('index', { title: 'Express' });
  //   console.log("req",req);
  //   console.info("ip",getClientIp(req))
  //   res.status(200).json({'name':'kinglong'})

//
    //设置请求的返回头type,content的type类型列表见上面
    res.setHeader("Content-Type", "image/png");
// //格式必须为 binary 否则会出错
//     var content =  fs.readFileSync('public/images/test.png',"binary");
//     console.log("content",content)
//     res.writeHead(200, "Ok");
//     res.write(content,"binary"); //格式必须为 binary，否则会出错
//     res.end();
    var stream = fs.createReadStream( 'public/images/test.jpg' );
    var responseData = [];//存储文件流
    // var buf2 = new Buffer("Hello Buffer");
    if (stream) {//判断状态
        stream.on( 'data', function( chunk ) {
            responseData.push( chunk );
        });
        stream.on( 'end', function() {
            var finalData = Buffer.concat( responseData );
            res.write( finalData,'binary' );
           console.log("长度", Buffer.byteLength(finalData, 'utf8'));
            console.log("ffff",finalData.toString("hex"))
            res.end();
        });
    }
});
router.post('/upload', function(req, res) {
      let stream = req.body;
      let png = stream.file;
      console.log("png",png);
      png = png.replace(/ /g,"+");;
      //base64解码
      let pngImg = new Buffer(png, 'base64');
      console.log("pngImg",pngImg);
    let length = Buffer.byteLength(pngImg, 'utf8');
    console.log("长度", length);
    console.log("ffff",pngImg.toString("hex"))
    let width = Math.sqrt( length)
    let newBuffer = new Buffer(length)
    //循环buffer，转化为0，1
    for(let i=0;i<length;i++){
        // console.log("整形数据",pngImg.readUInt8(i))
        let intData = pngImg.readUInt8(i);
        let yu = intData%2;
        // console.log("yushu",yu)
        if(yu)
            newBuffer.writeUInt8(1,i);
        else
            newBuffer.writeUInt8(0,i);
    }
    console.log("转换后数据",newBuffer.toString("hex"))
    //转为二维数组
    let qrLevel = Math.sqrt(length);
    var data=new Array();
    for(var i=0;i<qrLevel;i++){
        data[i]=new Array();
        for(var j=0;j<qrLevel;j++){
            data[i][j]=newBuffer.readUInt8(qrLevel*i+j);
        }
    }
    console.log("转换后数组",data)
    //转换为png文件
    var bitmap = createPng.bitmap(data, 5, 4);
    var pngstream = new Readable();
    createPng.png(bitmap, pngstream);
    console.log("bb",bitmap)
    console.log("bb",pngstream)


    for(let i=0;i<width;i++){
        console.log("第"+i+"行",pngImg.slice(qrLevel*i, qrLevel*i+(qrLevel-1)))
        //取余计算

    }
    // 生成图片3(把base64位图片编码写入到图片文件)
    // fs.writeFile('public/images/test3.png', pngstream, function(err) {
    //     if(err) {console.log(err)}
    // });
    var w = fs.createWriteStream('public/images/test3.png');
    pngstream.pipe(w);
    res.status(200).json({'name':'kinglong'})
})
var qr_image = require('qr-image');
router.get('/qrcode',function(req,res){
    var temp_qrcode = qr_image.image('你好啊美女');
    res.type('png');
    temp_qrcode.pipe(res);
})
module.exports = router;
function getClientIp(req) {
    return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
};

